package com.mipo.client.javase.company.flytek.beilun.openapi;

import org.apache.http.HttpEntity;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * 接口文档地址为：
 * 中心文档 http://dev.open.changyan.com/docenter/login
 * 区域文档 http://open.ewp.changyan.cn/docenter/api_list
 * 用户名和密码：reader/123456
 * 
 * 中心url：xxx
 * 区域url：http://open.blzy.bledu.net.cn/api；临沂和北仑都调用的是区域的openapi
 * 
 *
 * @author jack lee
 **/

public class BeiLunOpenApiTest {
	public static String HEAD_DESKTOP     = "http://open.blzy.bledu.net.cn/api?format=json&appkey=297654313c224575931f26991134b009&version=1.0&access_token=449eaf4a-f096-4dc0-8cc5-2499a8726c68&";
	public static String HEAD_APPSEARCH   = "http://open.blzy.bledu.net.cn/api?format=json&appkey=207afa88670449cbad5de149441528da&version=1.0&access_token=b9c0dfbc-7018-41b6-a169-cf2bc7278aec&";
	public static void main(String[] args) throws Exception {
		getOauthToken(); // 获取tokent
		coreUserGet(); // 获取用户信息
		//coreUcGetPhaseInfo(); // 获取学段信息
	}
	
	public static void coreUserGet() throws Exception {
		String url = HEAD_DESKTOP + "method=core.user.get&key=loginName&value=beilun2";
		excuteGetRequest(url);
	}
	
	public static void coreUcGetPhaseInfo() throws Exception {
		String url = HEAD_APPSEARCH + "method=core.uc.get.phase.info";
		excuteGetRequest(url);
	}
	
	public static void getOauthToken() throws Exception {
		// 这个是desk-top的app key
		String url = "http://open.blzy.bledu.net.cn/authorization-token-server/oauth/token?client_id=297654313c224575931f26991134b009&client_secret=7ef34026e1fd57eb95efb7d7cadb9c38&grant_type=client_credentials";
		// 这个是App Search的app key
		String url2 = "http://open.blzy.bledu.net.cn/authorization-token-server/oauth/token?client_id=207afa88670449cbad5de149441528da&client_secret=54521d0fbd2e6a1a6899bc99927c3b44&grant_type=client_credentials";
		excuteGetRequest(url2); // 返回desk-top的token为：ef150324-515d-4b3d-a4be-475733214b33；返回App Search的token为：b9c0dfbc-7018-41b6-a169-cf2bc7278aec
	}
	
	public static void excuteGetRequest(String url) throws Exception {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpGet httpGet = new HttpGet(url);
		CloseableHttpResponse response = httpClient.execute(httpGet); // 4.3版本不设置超时的话，一旦服务器没有响应，等待时间N久(>24小时)。
		HttpEntity entity = response.getEntity(); // 返回报文实体
		StatusLine status = response.getStatusLine();
		System.out.println("返回的状态码为：" + status); // 具体返回码(200)为status.getStatusCode(); 
		String ret = EntityUtils.toString(entity); // 将返回报文实体转换为字符串
		System.out.println("返回的报文为：" + ret);
		EntityUtils.consume(entity);  // 释放是否可以去掉？
		response.close(); // 关闭资源,可以写在finally里
		httpGet.releaseConnection(); // 释放资源
		httpClient.close(); // 关闭资源
	}
	
	
	
	
}
